package com.zan.ojstudy.zanojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.sun.management.OperatingSystemMXBean;
import com.zan.ojstudy.zanojcodesandbox.model.ExecuteCodeRequest;
import com.zan.ojstudy.zanojcodesandbox.model.ExecuteCodeResponse;
import com.zan.ojstudy.zanojcodesandbox.model.ExecuteMessage;
import com.zan.ojstudy.zanojcodesandbox.model.JudgeInfo;
import com.zan.ojstudy.zanojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author : Zan
 * @Create : 2024/6/4 20:10
 * @ClassName : JavaCodeSandBoxTemplate
 * @Description : TODO 请用一句话描述该类的功能
 */
@Slf4j
public abstract class JavaCodeSandBoxTemplate implements CodeSandBox {

    // 全局代码目录名称
    public static final String GLOBAL_CODE_DIR_NAME = "tempCode";
    // Java的全局类名
    public static final String GLOBAL_JAVA_CLASS_NAME = "Solution.java";
    // 超时时间
    private static final Long TIME_OUT = 5000L;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();

        //（1）把用户的代码保存为文件
        File userCodeFile = saveCodeToFile(code);

        //（2）编译代码，得到 .class 文件（编译）
        ExecuteMessage compileFileExecuteMessage = compileFile(userCodeFile);
        System.out.println(compileFileExecuteMessage);

        //（3）执行程序，得到输出结果（运行）
        List<ExecuteMessage> executeMessageList = runFile(userCodeFile, inputList);
        System.out.println(executeMessageList);

        //（4）整理数据输出
        ExecuteCodeResponse executeCodeResponse = getOutputResponse(executeMessageList);
        System.out.println(executeCodeResponse);

        //（5）文件清理
        boolean b = deleteFile(userCodeFile);
        if (!b) {
            log.error("deleteFile error, userCodeFilePath = {}", userCodeFile.getAbsoluteFile());
        }
        return executeCodeResponse;
    }

    /**
     * （1）把用户的代码保存为文件
     *
     * @param code
     * @return
     */
    public File saveCodeToFile(String code) {
        // 获取根目录 F:\Java\Project\My\zan-oj-code-sandbox
        String userDir = System.getProperty("user.dir");
        // 全局代码目录
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在（第一次不存在）
        if (FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        // 把用户的代码隔离存在 - 存用户代码文件的文件夹
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        // 写入文件
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        return userCodeFile;
    }

    /**
     * （2）编译代码，得到 .class 文件（编译）
     *
     * @param userCodeFile
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile) {
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsoluteFile());
        try {
            // compileProcess 编译进程
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            if (executeMessage.getExistValue() != 0) {
                throw new RuntimeException("编译错误");
            }
            return executeMessage;
        } catch (Exception e) {
            // todo return getErrorResponse(e);
            throw new RuntimeException(e);
        }
    }

    /**
     * （3）执行程序，得到输出结果（运行）
     *
     * @param userCodeFile
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Solution %s", userCodeParentPath, inputArgs);
//            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Solution %s", userCodeParentPath, SECURITY_MANAGER_PATH, SECURITY_MANAGER_CLASS_NAME, inputArgs);
            try {
                // Runtime.getRuntime() 开启了一个新的子进程
                Process runProcess = Runtime.getRuntime().exec(runCmd);

                // 超时控制
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("超时了，进行中断");
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }).start();

                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
                throw new RuntimeException("程序执行异常", e);
            }
        }
        return executeMessageList;
    }

    /**
     * （4）整理数据输出
     *
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 取用时最大时，判断是否超时
        Long maxTime = 0L;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                // 有报错信息
                executeCodeResponse.setMessage(errorMessage);
                // 用户提交的代码执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            if (executeMessage.getTime() != null) {
                maxTime = Math.max(maxTime, executeMessage.getTime());
            }
        }
        // 正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);

        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        // 要借助第三方库来获取内存占用，非常麻烦
        judgeInfo.setMemory(getMemoryUsage());

        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    /**
     * （5）文件清理
     *
     * @param userCodeFile
     * @return
     */
    public boolean deleteFile(File userCodeFile) {
        if (userCodeFile.getParentFile().exists()) {
            String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }

    /**
     * （6）获取错误响应
     *
     * @param e
     * @return
     */
    public ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误（例如编译错误）
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

    /**
     * 获取内存使用情况
     *
     * @return
     */
    private long getMemoryUsage() {
        OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);

        // 获取总的物理内存大小（字节）
        long totalPhysicalMemorySize = osBean.getTotalPhysicalMemorySize();

        // 获取空闲的物理内存大小（字节）
        long freePhysicalMemorySize = osBean.getFreePhysicalMemorySize();

        // 计算已使用的物理内存大小（字节）
        long usedPhysicalMemorySize = totalPhysicalMemorySize - freePhysicalMemorySize;

        // 将字节转换为MB并返回
        return usedPhysicalMemorySize / (1024 * 1024);
    }
}
